import React, { useContext, useEffect, useState } from "react"
import { Link, useNavigate, useParams } from "react-router-dom";
import { UserContext } from "../context/userContext";
import axios from "axios";
import Spinner from '../components/Spinner';
import DeletePost from "./DeletePost";
import PostItem from "../components/PostItem";
import {Badge, Card, NavBar, Tag} from "antd-mobile";
import {LeftOutline} from "antd-mobile-icons";

const Dashboard = () => {
  const [posts, setPosts] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const {id} = useParams();
  const colors = {'applied':'rgba(80, 62, 157, 1)', 'approved':'rgba(251, 110, 58, 1)', 'failed':'rgba(255, 0, 0, 1)', 'closed':'rgba(255, 0, 0, 1)'};
  const status = {'applied':'待审核', 'approved':'已通过', 'failed':'未通过', 'closed':'已关闭'};
  const {currentUser} = useContext(UserContext)
  const token = currentUser?.token
  const navigate = useNavigate()
  const back = () =>{
    navigate(-1);
  }
  useEffect(() => {
    if (!token) {
      navigate('/login')
    }
  }, [])

  useEffect(() => {
    const fetchPosts = async () => {
      setIsLoading(true);

      try {
        const response = await axios.get(`${process.env.REACT_APP_BASE_URL}/posts/myposts/${id}`, {withCredentials: true, headers: {Authorization: `Bearer ${token}`}});
        setPosts(response.data);
      } catch (error) {
        console.log(error);
      }

      setIsLoading(false);
    }

    fetchPosts()
  }, [id])

  if (isLoading) {
    return <Spinner />
  }

  return (
      <section className='posts'>
        <NavBar style={{'background-color': 'rgba(80, 62, 157, 1)', 'color': 'white'}} onBack={back}>我参与的项目</NavBar>

        {posts.length > 0 ? <div className='container posts__container'>
          {posts.map(({_id: id, apply, wages, deadline, title, description, avatar, creator, createdAt,views,applies}) =>
              <div>
               <Tag style={{'float':'right','position':'relative','top':'20px'}} color={colors[apply]}>{status[apply]}</Tag>
                <PostItem key={id}
                          postID={id}
                          deadline={deadline}
                          title={title}
                          views={views}
                          applies={applies}
                          wages={wages}
                          description={description}
                          authorID={creator}
                          createdAt={createdAt}
                          avatar={avatar}
                /></div>)}
        </div> : <h2 className='center'>No posts founds</h2>}
      </section>
  )
}

export default Dashboard
